import React, { useState, useEffect, useCallback, useMemo } from 'react'
import { Layout, Card, Spin, Empty, message, Button, Tooltip } from 'antd'
import { MenuFoldOutlined, MenuUnfoldOutlined, ReloadOutlined } from '@ant-design/icons'
import styles from './ScriptManager.module.css'
import { useAppSelector, useAppDispatch } from '@/store'
import { 
  fetchScripts, 
  setCurrentScript, 
  setSearchKeyword, 
  setSelectedTags, 
  setCurrentFolderId 
} from '@/store/slices/scriptSlice'
import { Script } from '@/types/script'
import { Folder } from '@/types/folder'
import FolderTree from './FolderTree'
import ScriptList from './ScriptList'
import SearchAndFilter from './SearchAndFilter'
import ScriptToolbar from './ScriptToolbar'
import { batchOperateScripts } from '@/services/scriptAPI'

const { Sider, Content } = Layout

interface ScriptManagerMainProps {
  onScriptSelect?: (script: Script) => void
  onScriptExecute?: (script: Script) => void
  selectedScriptId?: string
  height?: number
}

interface FilterOptions {
  dateRange?: [string, string]
  createdBy?: string[]
  hasDescription?: boolean
  hasContent?: boolean
  minVersions?: number
  maxVersions?: number
  lastExecutedRange?: [string, string]
  contentLength?: {
    min?: number
    max?: number
  }
}

const ScriptManagerMain: React.FC<ScriptManagerMainProps> = ({
  onScriptSelect,
  onScriptExecute,
  selectedScriptId,
  height = 600,
}) => {
  const dispatch = useAppDispatch()
  const { 
    scripts, 
    loading, 
    currentScript, 
    searchKeyword: storeSearchKeyword,
    selectedTags: storeSelectedTags,
    currentFolderId: storeCurrentFolderId,
  } = useAppSelector(state => state.script)
  const { theme } = useAppSelector(state => state.ui)
  
  // 本地状态管理
  const [selectedFolder, setSelectedFolder] = useState<Folder | null>(null)
  const [sortBy, setSortBy] = useState<'name' | 'created_at' | 'updated_at' | 'last_executed_at'>('updated_at')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
  const [selectedScripts, setSelectedScripts] = useState<string[]>([])
  const [siderCollapsed, setSiderCollapsed] = useState(false)
  const [filterOptions, setFilterOptions] = useState<FilterOptions>({})
  const [refreshing, setRefreshing] = useState(false)

  // 从store获取当前状态
  const searchKeyword = storeSearchKeyword
  const selectedTags = storeSelectedTags
  const selectedFolderId = storeCurrentFolderId

  // 加载脚本列表
  const loadScripts = useCallback(async () => {
    try {
      await dispatch(fetchScripts({
        keyword: searchKeyword || undefined,
        tags: selectedTags.length > 0 ? selectedTags : undefined,
        folderId: selectedFolderId || undefined,
        limit: 100,
        offset: 0,
        ...filterOptions,
      }))
    } catch (error) {
      console.error('加载脚本列表失败:', error)
      message.error('加载脚本列表失败')
    }
  }, [dispatch, searchKeyword, selectedTags, selectedFolderId, filterOptions])

  // 处理文件夹选择
  const handleFolderSelect = useCallback((folderId: string | null, folder: Folder | null) => {
    dispatch(setCurrentFolderId(folderId))
    setSelectedFolder(folder)
    setSelectedScripts([]) // 清除选中的脚本
  }, [dispatch])

  // 处理脚本选择
  const handleScriptSelect = useCallback((script: Script) => {
    dispatch(setCurrentScript(script))
    onScriptSelect?.(script)
  }, [dispatch, onScriptSelect])

  // 处理脚本执行
  const handleScriptExecute = useCallback((script: Script) => {
    onScriptExecute?.(script)
  }, [onScriptExecute])

  // 处理搜索
  const handleSearch = useCallback((keyword: string) => {
    dispatch(setSearchKeyword(keyword))
  }, [dispatch])

  // 处理标签变化
  const handleTagsChange = useCallback((tags: string[]) => {
    dispatch(setSelectedTags(tags))
  }, [dispatch])

  // 处理排序变化
  const handleSortChange = useCallback((newSortBy: string, newSortOrder: 'asc' | 'desc') => {
    setSortBy(newSortBy as any)
    setSortOrder(newSortOrder)
  }, [])

  // 处理过滤器变化
  const handleFilterChange = useCallback((filters: FilterOptions) => {
    setFilterOptions(filters)
  }, [])

  // 处理批量操作
  const handleBulkOperation = useCallback(async (operation: string, scriptIds: string[]) => {
    if (scriptIds.length === 0) {
      message.warning('请先选择要操作的脚本')
      return
    }

    try {
      let response
      switch (operation) {
        case 'delete':
          response = await batchOperateScripts({
            script_ids: scriptIds,
            operation: 'delete',
          })
          if (response.success) {
            message.success(`成功删除 ${response.data.success_count} 个脚本`)
            if (response.data.failed_count > 0) {
              message.warning(`${response.data.failed_count} 个脚本删除失败`)
            }
          }
          break
        
        case 'move':
          // 这里需要用户选择目标文件夹
          message.info('请选择目标文件夹后再进行移动操作')
          return
        
        case 'update_tags':
          // 这里需要用户输入标签
          message.info('请输入要添加的标签')
          return
        
        default:
          message.warning('未知操作')
          return
      }
      
      setSelectedScripts([])
      loadScripts()
    } catch (error) {
      console.error(`批量操作失败: ${operation}`, error)
      message.error(`批量操作失败: ${operation}`)
    }
  }, [loadScripts])

  // 刷新数据
  const handleRefresh = useCallback(async () => {
    setRefreshing(true)
    try {
      await loadScripts()
      message.success('刷新成功')
    } catch (error) {
      message.error('刷新失败')
    } finally {
      setRefreshing(false)
    }
  }, [loadScripts])

  // 脚本创建成功回调
  const handleScriptCreated = useCallback(() => {
    loadScripts()
  }, [loadScripts])

  // 处理脚本选中状态变化
  const handleScriptSelectionChange = useCallback((scriptIds: string[]) => {
    setSelectedScripts(scriptIds)
  }, [])

  // 初始化加载
  useEffect(() => {
    loadScripts()
  }, [loadScripts])

  // 响应式布局计算
  const siderWidth = siderCollapsed ? 0 : 280
  const layoutStyle = useMemo(() => ({
    height: height,
    background: 'transparent',
  }), [height])

  const siderStyle = useMemo(() => ({
    background: theme === 'dark' ? '#1f1f1f' : '#fff',
    borderRight: `1px solid ${theme === 'dark' ? '#303030' : '#f0f0f0'}`,
    overflow: 'auto' as const,
    position: 'relative' as const,
  }), [theme])

  const contentStyle = useMemo(() => ({
    display: 'flex',
    flexDirection: 'column' as const,
    height: '100%',
    padding: '0 16px 16px 16px',
  }), [])

  // 计算统计信息
  const statsInfo = useMemo(() => {
    const total = scripts.length
    const selected = selectedScripts.length
    const folderName = selectedFolder?.name || '所有脚本'
    
    return {
      total,
      selected,
      folderName,
      hasFilter: searchKeyword || selectedTags.length > 0 || Object.keys(filterOptions).length > 0,
    }
  }, [scripts.length, selectedScripts.length, selectedFolder, searchKeyword, selectedTags, filterOptions])

  return (
    <Layout className={styles.scriptManagerLayout} style={layoutStyle}>
      {/* 左侧文件夹树 */}
      <Sider
        width={280}
        collapsible
        collapsed={siderCollapsed}
        onCollapse={setSiderCollapsed}
        collapsedWidth={0}
        className={styles.sider}
        style={siderStyle}
        trigger={null}
      >
        <div className={styles.siderContent}>
          {/* 折叠按钮 */}
          <div className={styles.siderHeader}>
            <Tooltip title={siderCollapsed ? '展开' : '收起'}>
              <Button
                type="text"
                size="small"
                icon={siderCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setSiderCollapsed(!siderCollapsed)}
              />
            </Tooltip>
          </div>
          
          {/* 文件夹树 */}
          <div className={styles.siderBody}>
            <FolderTree
              onFolderSelect={handleFolderSelect}
              selectedFolderId={selectedFolderId}
              showSearch={true}
              allowEdit={true}
              allowDrag={true}
              height={height - 100}
            />
          </div>
        </div>
      </Sider>

      {/* 主内容区域 */}
      <Layout>
        <Content className={styles.content}>
          {/* 顶部工具栏 */}
          <div className={styles.toolbar} data-theme={theme}>
            <div className={styles.toolbarLeft}>
              {/* 折叠按钮（当侧边栏收起时显示） */}
              {siderCollapsed && (
                <Tooltip title="展开文件夹">
                  <Button
                    type="text"
                    icon={<MenuUnfoldOutlined />}
                    onClick={() => setSiderCollapsed(false)}
                  />
                </Tooltip>
              )}
              
              {/* 当前位置和统计信息 */}
              <div>
                <span className={styles.toolbarTitle}>
                  {statsInfo.folderName}
                </span>
                <span className={styles.toolbarStats}>
                  {statsInfo.hasFilter ? `筛选出 ${statsInfo.total} 项` : `共 ${statsInfo.total} 项`}
                  {statsInfo.selected > 0 && ` · 已选择 ${statsInfo.selected} 项`}
                </span>
              </div>
            </div>

            {/* 右侧操作按钮 */}
            <div>
              <Tooltip title="刷新">
                <Button
                  type="text"
                  icon={<ReloadOutlined />}
                  loading={refreshing}
                  onClick={handleRefresh}
                />
              </Tooltip>
            </div>
          </div>

          {/* 搜索和过滤器 */}
          <Card 
            size="small" 
            className={styles.searchCard}
            bodyStyle={{ padding: '16px' }}
          >
            <SearchAndFilter
              onSearch={handleSearch}
              onTagsChange={handleTagsChange}
              onSortChange={handleSortChange}
              onFilterChange={handleFilterChange}
              defaultKeyword={searchKeyword}
              defaultTags={selectedTags}
              defaultSortBy={sortBy}
              defaultSortOrder={sortOrder}
              showAdvancedFilter={true}
              showSortOptions={true}
              showSaveSearch={true}
            />
          </Card>

          {/* 工具栏 */}
          <Card 
            size="small" 
            className={styles.scriptToolbarCard}
            bodyStyle={{ padding: 0 }}
          >
            <ScriptToolbar
              selectedScripts={selectedScripts}
              currentFolderId={selectedFolderId}
              onRefresh={handleRefresh}
              onScriptCreated={handleScriptCreated}
              onBulkOperation={handleBulkOperation}
            />
          </Card>

          {/* 脚本列表 */}
          <Card 
            className={styles.scriptListCard}
            bodyStyle={styles.scriptListCardBody}
          >
            {loading ? (
              <div className={styles.loadingContainer}>
                <Spin size="large" />
              </div>
            ) : (
              <div className={styles.scriptListContainer}>
                <ScriptList
                  folderId={selectedFolderId}
                  searchKeyword={searchKeyword}
                  selectedTags={selectedTags}
                  sortBy={sortBy}
                  sortOrder={sortOrder}
                  onScriptSelect={handleScriptSelect}
                  onScriptExecute={handleScriptExecute}
                  onSelectionChange={handleScriptSelectionChange}
                  selectedScriptId={selectedScriptId}
                  allowDrag={true}
                  allowBulkSelect={true}
                  pageSize={20}
                />
              </div>
            )}
          </Card>
        </Content>
      </Layout>
    </Layout>
  )
}

export default ScriptManagerMain